import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
    getProducts,
    addProduct as addProductAPI,
    updateProduct as updateProductAPI,
    deleteProduct as deleteProductAPI,
    getProductData as getProductDataAPI,
    getCategoryData
} from '@/apis/product'

export const useProductStore = defineStore('product', () => {

    const products = ref([])

    // 获取商品列表
    const fetchProducts = async () => {
        try {
            const res = await getProducts()
            if (res.code === 200) {
                products.value = res.data
                return res.data; //响应拦截器已经处理了一个data
            }
            throw new Error(res.message || '获取商品列表失败')
        } catch (error) {
            console.error('获取商品列表错误:', error)
            throw error
        }
    }

    // 添加商品
    const addProduct = async (productData) => {
        try {
            const res = await addProductAPI(productData)
            if (res.code === 200) {
                await fetchProducts() // 刷新列表
                return res  //采用响应拦截器的data
            }
            throw new Error(res.message || '添加商品失败')
        } catch (error) {
            console.error('添加商品错误:', error)
            throw error
        }
    }

    // 更新商品
    const updateProduct = async (productId, productData) => {
        try {
            const res = await updateProductAPI(productId, productData)
            if (res.code === 200) {
                await fetchProducts()
                return res
            }
            throw new Error(res.message || '更新商品失败')
        } catch (error) {
            console.error('更新商品错误:', error)
            throw error
        }
    }

    // 删除商品
    const deleteProduct = async (productId) => {
        try {
            const res = await deleteProductAPI(productId)
            if (res.code === 200) {
                await fetchProducts()
                return res
            }
            throw new Error(res.message || '删除商品失败')
        } catch (error) {
            console.error('删除商品错误:', error)
            throw error
        }
    }


    // 获取产品统计数据
    const fetchProductData = async () => {
        try {
            const response = await getProductDataAPI()
            return response
        } catch (error) {
            console.error('获取产品统计数据失败:', error)
            throw error
        }
    }

    // 获取分类统计数据
    const fetchCategoryData = async () => {
        try {
            const res = await getCategoryData()
            return res
        } catch (error) {
            console.error('获取分类数据失败:', error)
            throw error
        }
    }

    return {
        products,
        fetchProducts,
        addProduct,
        updateProduct,
        deleteProduct,
        fetchProductData,
        fetchCategoryData
    }
})